package com.xyh.config;

import com.xyh.bean.Constants;
import com.xyh.utils.PropertiesUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DatabaseConfig {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);
    private static HikariDataSource dataSource;

    static {
        initDataSource();
    }

    private static void initDataSource() {
        try {
            HikariConfig config = new HikariConfig();
            config.setDriverClassName(Constants.DB_DRIVER_NAME);
            config.setJdbcUrl(Constants.DB_URL);
            config.setUsername(Constants.DB_USERNAME);
            config.setPassword(Constants.DB_PASSWORD);
            
            // 连接池配置
            config.setMaximumPoolSize(10);
            config.setMinimumIdle(5);
            config.setIdleTimeout(300000);
            config.setConnectionTimeout(20000);
            config.setMaxLifetime(1200000);
            
            dataSource = new HikariDataSource(config);
            logger.info("数据库连接池初始化成功");
        } catch (Exception e) {
            logger.error("数据库连接池初始化失败", e);
            throw new RuntimeException("数据库连接池初始化失败", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            throw new SQLException("数据源未初始化");
        }
        return dataSource.getConnection();
    }

    public static void closeDataSource() {
        if (dataSource != null) {
            dataSource.close();
            logger.info("数据库连接池已关闭");
        }
    }
} 